import React, {Component} from 'react'
import {Col, Icon, Row, Tabs} from 'antd'
import {TwsBelongTask} from 'tws-antd'
import {connect} from 'react-redux'
import '../less/index.less'
import {withRouter} from 'react-router-dom'
import MultipleChoiceQuiz from './common/multiple-choice-quiz'
import SingleChoiceQuiz from './common/single-choice-quiz'
import BasicBlankQuiz from './common/basic-blank-quiz'
import EditStatusBox from './common/edit-status-box'
import UrlPattern from 'url-pattern'
import * as taskActions from '../actions/task'
import * as assignment from '../actions/assignment'
import * as userActions from '../actions/user'
import AssignmentSupplementaryBox from './common/assignment-supplementary-box'
import {getSectionComments} from '../actions/comment'
import CommentBox from './common/comment-box'
import {FormattedMessage} from 'react-intl'
import {getLangFromLocalStorage} from '../constant/lang-util'
import AssignmentTagBox from './common/assignment-tag-box'
import AssignmentEvaluateBox from './common/assignment-evaluate-box'
import AssignmentRankingBox from './common/assignment-ranking-box'
import * as assignmentQuizMarkAction from '../actions/assignment-quiz-Mark'
import QuizNoteModal from './quiz-note-modal'
import {submitNote} from "../actions/notes";

const TabPane = Tabs.TabPane
class AssignmentPageBody extends Component {
  constructor (props) {
    super(props)
    this.state = {
      sectionId: 0,
      programId: 0,
      studentId: 0,
      taskId: 0,
      assignmentId: 0,
      quizId: 0,
      isQuizNoteModalVisible: false,
      noteContent: ''
    }
  }

  componentWillMount () {
    const pattern = new UrlPattern('/tutor/program/:programId/task/:taskId/student/:studentId/assignment/:assignmentId/quiz/:quizId')
    const urlParams = pattern.match(this.props.location.pathname.replace('divider/', '')) || {}
    this.setState({
      assignmentId: urlParams.assignmentId,
      studentId: urlParams.studentId,
      taskId: urlParams.taskId,
      programId: urlParams.programId,
      quizId: urlParams.quizId
    }, () => {
      const { taskId, assignmentId, studentId } = this.state
      this.props.getTaskInfo(taskId)
      this.props.getBasicQuizAssignment(assignmentId, studentId)
      this.props.tutorGetStudentReviewQuiz(studentId, assignmentId)
      this.props.getStudent(studentId)
      const quizId = assignmentId
      this.props.getComments(assignmentId, studentId, quizId)
      this.props.getAssignmentQuizMark(assignmentId, quizId, studentId)
    })
  }
  getCompleteName (student) {
    const name = student.name || ''
    const userName = student.userName || ''

    return `${name}(@${userName})`
  }

  showModal = () => {
    this.setState({
      isQuizNoteModalVisible: true,
    });
  };

  handleOk = () => {
    this.setState({
      isQuizNoteModalVisible: false,
    });
    this.handleSubmit()
  };

  handleCancel = () => {
    this.setState({
      isQuizNoteModalVisible: false,
    });
  };

  handleSubmit = () => {
    const {noteContent} = this.state
    const {assignment, taskInfo, user} =this.props
    const {assignmentId, studentId, taskId} = assignment.reviewQuiz
    const quizId = assignment.basicQuizzes[0].id
    const {programId} = taskInfo.task
    const tutorId = user.userId
    const quizType = 'BASIC_QUIZ'
    const values = {programId, taskId, assignmentId, quizId, studentId, tutorId, quizType, noteContent}
    this.props.submitNote(values)
  };

  handelChangeNote(value) {
    this.setState({
      noteContent: value
    })
  }

  render () {
    const {suggestions, assignment, assignmentQuizMark} = this.props
    const { basicQuizzes, reviewQuiz, student } = assignment
    const { task } = this.props.taskInfo
    const { tutorUrl } = this.props.settings
    const assignments = task.assignments || []
    const currentAssignment = assignments.find(assignment => assignment.id === parseInt(this.state.assignmentId)) || {}
    const completeName = this.getCompleteName(student)
    const type = 'tutor'
    const {studentId, assignmentId, programId, quizId, isQuizNoteModalVisible} = this.state
    const quizMap = {
      'SINGLE_CHOICE': SingleChoiceQuiz,
      'MULTIPLE_CHOICE': MultipleChoiceQuiz,
      'BASIC_BLANK_QUIZ': BasicBlankQuiz
    }
    const lang = getLangFromLocalStorage()

    return <div>
      <div>
        <Row >
          <Col span={8}>
            <h2>{currentAssignment[`title_${lang}`] || currentAssignment.title }</h2>
          </Col>
          <Col span={6} offset={10}>
            <EditStatusBox reviewQuiz={reviewQuiz} disable />
          </Col>
        </Row>
        <Row >
          <Col>
            <div><Icon type='user' /> {completeName}</div>
          </Col>
        </Row>
      </div>

      <TwsBelongTask title={<FormattedMessage id={'所属任务卡'} />}>
        <a
          href={tutorUrl + `/program/${this.state.programId}/task/${this.state.taskId}/student/${this.state.studentId}`}>
          <Icon type='arrow-left' />
          {task[`title_${lang}`] || task.title}
        </a>
        <AssignmentTagBox
          programId={programId}
          assignmentId={assignmentId}
          quizId={quizId}
          studentId={studentId}
        />
      </TwsBelongTask>

      <div className='margin-t-3'>
        <Row>
          <Col span={2}>
            <h3><FormattedMessage id={'作业内容'} /></h3>
          </Col>
          <Col span={4}>
            {
              reviewQuiz.id !== null ? <a onClick={this.showModal}><FormattedMessage id='添加备忘录'/></a> : ''
            }
          </Col>
          <QuizNoteModal isQuizNoteModalVisible={isQuizNoteModalVisible}
            handleOk={this.handleOk}
            handleCancel={this.handleCancel}
            handelChangeNote={this.handelChangeNote.bind(this)} />
        </Row>
        {
          reviewQuiz.id
            ? <span className='submit-time-box'>
              <Icon type='clock-circle' />
              {reviewQuiz.createTime}
            </span>
            : ''
        }
        <div className='margin-t-2'>
          <div style={{ background: 'white' }} />
          {
            basicQuizzes.map((quiz, index) => {
              const QuizComponent = quizMap[quiz.type]
              return <QuizComponent key={index} index={index} quiz={quiz} isTutor />
            })
          }
        </div>
      </div>
      <AssignmentSupplementaryBox
        reviewQuizId={reviewQuiz.id}
        reviewQuiz={reviewQuiz}
        userType={type}
      />
      <AssignmentRankingBox
        programId={programId}
        assignmentId={assignmentId}
        quizId={quizId}
        studentId={studentId}
        assignmentQuizMark={assignmentQuizMark}
        /><br />
      <Tabs defaultActiveKey='1' type='card' >
        <TabPane tab={<h4><FormattedMessage id='助教反馈' /></h4>} key='1'>
          <CommentBox
            suggestions={suggestions}
            isTutor
            user={this.props.user}
            programId={this.state.programId}
            taskId={this.state.taskId}
            assignmentId={assignmentId}
            studentId={studentId}
            quizId={assignmentId}
                />
        </TabPane>
        <TabPane tab={<h4><FormattedMessage id='隐藏评价' /></h4>} key='2'>
          <AssignmentEvaluateBox
            programId={programId}
            assignmentId={assignmentId}
            quizId={quizId}
            studentId={studentId}
            assignmentQuizMark={assignmentQuizMark}
                />
        </TabPane>
      </Tabs>

    </div>
  }
}

const mapStateToProps = ({ user, taskInfo, assignment, comments, settings, assignmentQuizMark }) => ({
  user,
  taskInfo,
  assignment,
  settings,
  suggestions: comments,
  assignmentQuizMark
})
const mapDispatchToProps = dispatch => ({
  getTaskInfo: (taskId) => dispatch(taskActions.getTaskInfo(taskId)),
  getBasicQuizAssignment: (assignmentId, studentId) => dispatch(assignment.getMyStudentAssignment(assignmentId, studentId)),
  tutorGetStudentReviewQuiz: (studentId, assignmentId) => dispatch(assignment.tutorGetStudentReviewQuiz(studentId, assignmentId)),
  getStudent: (studentId) => dispatch(userActions.getCurrentStudent(studentId)),
  getComments: (assignmentId, studentId, quizId) => dispatch(getSectionComments(assignmentId, studentId, quizId)),
  getAssignmentQuizMark: (assignmentId, quizId, studentId) => dispatch(assignmentQuizMarkAction.getAssignmentQuizMark(assignmentId, quizId, studentId)),
  submitNote: quizNote => dispatch(submitNote(quizNote))
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(AssignmentPageBody))
